package com.zhm.demo.minio;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author huf
 */
@Slf4j
public class MinioTemplateCommon {

    @Data
    public static final class OssConfigCommon {
        public String endpoint;
        public String accessKeyId;
        public String accessKeySecret;
        public String bucket;
    }

    private static OssConfigCommon makeOssConfigCommon() {
        OssConfigCommon ossConfigCommon = new OssConfigCommon();
        ossConfigCommon.setEndpoint("http://172.24.73.24:9090");
        ossConfigCommon.setAccessKeyId("admin");
        ossConfigCommon.setAccessKeySecret("admin123456");
        ossConfigCommon.setBucket("hero-iot-oss-sit");
        return ossConfigCommon;
    }

    /**
     * 获取文件大小-new
     *
     * @param bucketName
     */
    public static GetObjectResponse getFile(String bucketName, String ossPath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        OssConfigCommon ossConfigCommon = makeOssConfigCommon();
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint(ossConfigCommon.getEndpoint())
                .credentials(ossConfigCommon.getAccessKeyId(), ossConfigCommon.getAccessKeySecret())
                .build();
        GetObjectResponse obj = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(ossPath).build());
        System.out.println(obj.headers());
        return obj;
    }

    private static void inputStream2File(String saveDirectoryPath, GetObjectResponse getObjectResponse) {
        File saveDirectory = new File(saveDirectoryPath);
        if (!saveDirectory.exists()) {
            saveDirectory.mkdirs(); // 创建目录，如果目录不存在
        }

        String fileName = new File(getObjectResponse.object()).getName();
        try (InputStream inputStream = getObjectResponse) {

            File outputFile = new File(saveDirectory, fileName);
            //log.info("文件下载绝对路径为=== {}", outputFile.getAbsoluteFile());

            try (OutputStream outputStream = new FileOutputStream(outputFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to write file: " + fileName, e);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to download file: " + fileName, e);
        }
    }

    public static void uploadFile(String bucketName, String ossPath, String filePath) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        OssConfigCommon ossConfigCommon = makeOssConfigCommon();
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint(ossConfigCommon.getEndpoint())
                .credentials(ossConfigCommon.getAccessKeyId(), ossConfigCommon.getAccessKeySecret())
                .build();
        minioClient.uploadObject(
                UploadObjectArgs.builder()
                        .bucket(bucketName)
                        .object(ossPath)
                        .filename(filePath)
                        .build());
    }

    public static void testFileInfo(String bucketName, String ossPath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        OssConfigCommon ossConfigCommon = makeOssConfigCommon();
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint(ossConfigCommon.getEndpoint())
                .credentials(ossConfigCommon.getAccessKeyId(), ossConfigCommon.getAccessKeySecret())
                .build();
        StatObjectResponse fileSizeNew2 = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(ossPath).build());
        System.out.println(fileSizeNew2.etag());
    }

    public static String testG(String bucketName, String ossPath, Integer expiry) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        OssConfigCommon ossConfigCommon = makeOssConfigCommon();
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint(ossConfigCommon.getEndpoint())
                .credentials(ossConfigCommon.getAccessKeyId(), ossConfigCommon.getAccessKeySecret())
                .build();
        String url =
                minioClient.getPresignedObjectUrl(
                        GetPresignedObjectUrlArgs.builder()
                                .method(Method.PUT)
                                .bucket(bucketName)
                                .object(ossPath) //a.sh
                                .expiry(expiry)
                                .build());
        System.out.println(url);
        return url;
    }

    public static void main(String[] args) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//        String filePath = "D:\\jar\\demo-plugin-0.0.2-SNAPSHOT.jar";
//        File path = new File(filePath);

        String ossPath = "zhm/b.txt";

//        uploadFile(makeOssConfigCommon().getBucket(), ossPath, filePath);
//        GetObjectResponse getObjectResponse = getFile(makeOssConfigCommon().getBucket(), ossPath);
//        String basePath = System.getProperty("user.dir") + File.separator + "runData" + File.separator + "cache";
//        inputStream2File(basePath, getObjectResponse);
//        testFileInfo(makeOssConfigCommon().getBucket(), ossPath);

        testG(makeOssConfigCommon().getBucket(), ossPath, 60 * 60 * 1);
    }

}
